<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--公寓房间-->
      <el-col :span="24" :xs="24">
        <searchForm v-if="!floorId" :formOptions="formOptions" @onSearch="onSearch" @onReset="onReset"
          :formLabelWidth="formLabelWidth">
          <template>
            <el-form-item label="宿舍居住情况：">
              <el-select v-model="queryParams.liveStatus" placeholder="请选择宿舍居住情况" style="width: 100%">
                <el-option v-for="dict in dict.type.sys_room_live_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="房间类型：">
              <el-select v-model="queryParams.type" clearable filterable placeholder="请选择房间类型" style="width: 100%">
                <el-option v-for="dict in dict.type.sys_room_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="收费标准：">
              <el-select v-model="queryParams.feeType" clearable placeholder="请选择收费标准" style="width: 100%">
                <el-option v-for="dict in dict.type.sys_charging_standards" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="系统标识：">
              <el-select v-model="queryParams.systemMark" clearable filterable placeholder="请选择系统标识" style="width: 100%">
                <el-option v-for="dict in dict.type.dorm_room_flag" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="公寓楼名称：">
              <el-select  v-model="queryParams.houseId" :disabled="$route.query.houseId"
                placeholder="请选择公寓楼名称" style="width: 100%">
                <el-option v-for="dict in houseList" :key="dict.houseId" :label="dict.houseName"
                  :value="dict.houseId"></el-option>
              </el-select>
            </el-form-item>
          </template>
        </searchForm>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['dorm:room:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button size="mini" @click="allocation">一键分配</el-button>
          </el-col>-->
          <el-col :span="1.5">
            <!-- <el-button size="mini" @click="manualDistribution">手动分配</el-button> -->
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table :data="roomlist" @selection-change="handleSelectionChange" v-loading="loading">
          <el-table-column label="楼号" prop="houseName" :show-overflow-tooltip="true" align="center" />
          <el-table-column label="层号" prop="floorNo" align="center" />
          <el-table-column label="房间号" prop="roomNo" align="center" />
          <el-table-column label="收费标准" prop="feeType" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_charging_standards" :value="scope.row.feeType"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="房间类型" prop="type" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_room_type" :value="scope.row.type"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="系统标志" prop="systemMark" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.dorm_room_flag" :value="scope.row.systemMark"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="居住性别" prop="sex" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="宿舍居住情况" prop="liveStatus" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_room_live_status" :value="scope.row.liveStatus"></dict-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="240">
            <template slot-scope="scope" fixed="right">
              <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
                v-hasPermi="['dorm:room:edit']">修改</el-button>
              <el-button size="mini" type="text" @click="handleDelete(scope.row)"
                v-hasPermi="['dorm:room:remove']">删除</el-button>
              <el-button size="mini" type="text" @click="empty(scope.row)"
                v-hasPermi="['dorm:bed:remove']">一键清空</el-button>
              <el-button size="mini" type="text" @click="bedInfo(scope.row)"
                v-hasPermi="['dorm:bed:change']">床位信息</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
        <!-- 添加或修改公寓楼对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="110px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="楼号" prop="houseId">
                  <el-select @change="houseIdChange" v-model="form.houseId" :disabled="$route.query.houseId"
                    placeholder="请选择公寓楼名称" style="width: 100%">
                    <el-option v-for="dict in houseList" :key="dict.houseId" :label="dict.houseName"
                      :value="dict.houseId"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="层号" prop="floorId">
                  <el-select v-model="form.floorId" :disabled="$route.query.floorId" placeholder="请选择楼层号"
                    style="width: 100%">
                    <el-option v-for="dict in floorlist" :key="dict.floorId" :label="dict.floorNo"
                      :value="dict.floorId"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="房间号" prop="roomNo">
                  <el-input v-model="form.roomNo" placeholder="请输入房间号" maxlength="30" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="居住性别" prop="sex">
                  <el-select v-model="form.sex" clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                      :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="房间类型" prop="type">
                  <el-select v-model="form.type" clearable filterable placeholder="请选择" style="width: 100%">
                    <el-option v-for="dict in dict.type.sys_room_type" :key="dict.value" :label="dict.label"
                      :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="系统标志" prop="systemMark">
                  <el-select v-model="form.systemMark" clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="dict in dict.type.dorm_room_flag" :key="dict.value" :label="dict.label"
                      :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收费标准" prop="feeType">
                  <el-select v-model="form.feeType" clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="dict in dict.type.sys_charging_standards" :key="dict.value" :label="dict.label"
                      :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="open = false">取 消</el-button>
          </div>
        </el-dialog>
        <!-- 一键分配弹框 -->
        <el-dialog :title="title" :visible.sync="openAllocation" width="60%" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="60px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="院系" prop="nickName">
                  <!-- <el-select v-model="queryParams.value1" multiple placeholder="请选择院系" style="width: 100%">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>-->

                  <el-cascader ref="cascaderAddr" v-model="form.deptId" :options="deptOptions" style="width: 100%"
                    clearable :props="{ value: 'id', currentLabels: 'label' }" @change="handleChange"></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="班级" prop="nickName">
                  <el-select v-model="queryParams.value1" multiple placeholder="请选择班级" style="width: 100%">
                    <el-option v-for="item in options" :key="item.value" :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="nickName">
                  <el-select v-model="queryParams.value1" multiple placeholder="请选择性别" style="width: 100%">
                    <el-option v-for="item in options" :key="item.value" :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="楼栋" prop="nickName">
                  <el-select v-model="queryParams.value1" multiple placeholder="请选择楼栋" style="width: 100%">
                    <el-option v-for="item in options" :key="item.value" :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="openAllocation = false">取 消</el-button>
          </div>
        </el-dialog>
        <!-- 床位信息 -->
        <el-dialog :title="title" :visible.sync="openBed" top="20vh" width="70%" append-to-body>
          <allocationBeds style="min-height: 50vh;" :roomId="roomDataInfo ? roomDataInfo.roomId : null">
          </allocationBeds>
        </el-dialog>
      </el-col>
    </el-row>
    <!-- 手动分配 -->
    <el-dialog :title="title" :visible.sync="manualVisible" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="60px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="学号" prop="nickName">
              <el-input placeholder="请输入学号" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-button>验证</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="楼号" prop="nickName">
              <el-select v-model="queryParams.value1" multiple placeholder="请选择楼号" style="width: 100%">
                <el-option v-for="item in options" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房间号" prop="nickName">
              <el-select v-model="queryParams.value1" multiple placeholder="请选择房间号" style="width: 100%">
                <el-option v-for="item in options" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="manualVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import searchForm from "@/components/Search/searchForm.vue";
import treeIndex from "@/components/tree/index.vue";
import { mapState, mapActions } from "vuex";
import { deptTreeSelect } from "@/api/system/user";
import { studentList } from "@/api/information/studentInfor";
import allocationBeds from "./allocationBeds.vue";

export default {
  components: { searchForm, treeIndex, allocationBeds },
  data() {
    return {
      tabPosition: "left",
      options: [],
      deptOptions: [
        {
          label: "一级 1",
          id: 1,
          children: [
            {
              label: "二级 1-1",
              id: 2,
              children: [
                {
                  label: "三级 1-1-1"
                }
              ]
            }
          ]
        },
        {
          label: "一级 2",
          children: [
            {
              label: "二级 2-1",
              children: [
                {
                  label: "三级 2-1-1"
                }
              ]
            },
            {
              label: "二级 2-2",
              children: [
                {
                  label: "三级 2-2-1"
                }
              ]
            }
          ]
        },
        {
          label: "一级 3",
          children: [
            {
              label: "二级 3-1",
              children: [
                {
                  label: "三级 3-1-1"
                }
              ]
            },
            {
              label: "二级 3-2",
              children: [
                {
                  label: "三级 3-2-1"
                }
              ]
            }
          ]
        }
      ],
      roomDataInfo: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 一键分配弹出层
      openAllocation: false,
      // 手动分配弹出层
      manualVisible: false,
      // 床位分配
      bedAllcation: false,
      // 床位信息弹出层
      openBed: false,
      // 是否显示弹出层（数据权限）
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: null,
        roleKey: null,
        status: null,
        type: null,
        feeType: null,
        systemMark: null,
        houseId: null
      },
      // 查询数据
      formLabelWidth: "98px",
      formOptions: [
        {
          label: "房间号",
          prop: "roomNo",
          element: "el-input",
          placeholder: "请输入房间号"
        }
        // {
        //   label: "宿舍居住情况",
        //   prop: "liveStatus",
        //   element: "el-select",
        //   options: [
        //     { label: "未住满", value: "1" },
        //     { label: "已住满", value: "2" },
        //   ],
        //   placeholder: "请选择宿舍居住情况",
        // },
      ],
      // 表单参数
      form: {
        houseId: "",
        floorId: "",
        roomNo: "",
        type: "",
        feeType: ""
      },
      defaultProps: {
        children: "children",
        label: "label"
      },

      // 表单校验
      rules: {
        houseId: [{ required: true, message: "楼号不能为空", trigger: "blur" }],
        floorId: [{ required: true, message: "层号不能为空", trigger: "blur" }],
        roomNo: [
          { required: true, message: "房间号不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "房间类型不能为空", trigger: "change" }
        ],
        feeType: [
          { required: false, message: "收费标准不能为空", trigger: "blur" }
        ],
        sex: [
          { required: true, message: "请选择居住性别", trigger: "change" }
        ],
        systemMark: [
          { required: false, message: "请选择", trigger: "change" }
        ]
      }
    };
  },
  dicts: [
    "sys_charging_standards",
    "sys_room_type",
    "sys_room_live_status",
    "dorm_room_flag",
    'sys_charging_standards',
    'sys_user_sex',
  ],
  computed: {
    ...mapState({
      floorlist: state => state.apartmentFloor.list,
      houseList: state => state.apartmentBuilding.list,
      roomlist: state => state.apartmentRoom.list
    })
  },
  watch: {
    floorId: function () {
      this.queryParams.floorId = Number(this.$route.query.floorId) || null;
      this.getList();
    }
  },
  props: {
    floorId: {
      type: String
    }
  },
  async created() {
    await this.getHouseList();
    this.queryParams.floorId = Number(this.$route.query.floorId) || null;
    await this.getfloorList({
      houseId: this.$route.query.houseId || null
    });
    this.getList();
    this.department();
  },
  methods: {
    ...mapActions({
      getfloorList: "apartmentFloor/getTable",
      getTableList: "apartmentRoom/getTable",
      getHouseList: "apartmentBuilding/getTable",
      getAllUser: "getAllUser",
      addInfo: "apartmentRoom/addInfo",
      putInfoById: "apartmentRoom/putInfoById",
      delInfoById: "apartmentRoom/delInfoById",
      addBedInfo: "roomBedList/addInfo",
      deleteUseBedByRoomIds: "roomBedList/deleteUseBedByRoomIds",
      getAllRoom: "apartmentBuilding/allInfolist"
    }),
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      this.getTableList({ ...this.queryParams }).then(res => {
        this.total = res.total;
        this.loading = false;
      });
    },
    // 获取搜索表单提交的数据
    onSearch(val) {
      // 查询条件和分页数据合并
      const arr = Object.assign(this.queryParams, val);
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    onReset(data) {
      this.queryParams.pageNum = 1;
      this.queryParams.liveStatus = undefined;
      // const arr = Object.assign(this.queryParams, data);
      Object.assign(this.queryParams, this.$options.data().queryParams);

      this.getList();
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 表单重置
    reset() {
      this.form = this.$options.data().form;
      this.form.houseId = Number(this.$route.query.houseId) || null;
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加公寓房间";
      this.form.houseId = Number(this.$route.query.houseId) || null;
      this.form.floorId = Number(this.$route.query.floorId) || null;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      row.houseId = Number(row.houseId)
      this.reset();
      this.form = JSON.parse(JSON.stringify(row));
      this.open = true;
      this.title = "修改信息";
    },

    /** 提交按钮 */
    submitForm: function async() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          if (!this.form.roomId) {
            const { data, code } = await this.addInfo(this.form);
            if (code == 200) {
              this.$modal.msgSuccess("添加成功");
              this.open = false;
              this.getList();
              this.getAllRoom();
            }
          } else {
            const { data, code } = await this.putInfoById(this.form);
            if (code == 200) {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.getAllRoom();
            }
          }

          this.reset();
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.roomId || this.ids;
      this.$modal
        .confirm('是否确认删除名称为"' + row.roomNo + '"的数据项？')
        .then(async () => {
          const { data, code } = await this.delInfoById({ roomId: ids });
          this.getList();
          this.getAllRoom();
          this.$modal.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/role/export",
        {
          ...this.queryParams
        },
        `role_${new Date().getTime()}.xlsx`
      );
    },

    // tree树形选中的值
    handleNodeClick(data) {
      console.log(data.label, "选中的值");
    },

    // 一键分配弹窗
    allocation() {
      this.title = "一键分配";
      this.openAllocation = true;
    },
    // 手动分配
    manualDistribution() {
      this.title = "手动分配";
      this.manualVisible = true;
    },
    // 添加床位信息弹窗
    addBedInfor(roomId) {
      this.title = "添加房间信息";
      this.addBed = true;
    },
    bedInfo(row) {
      this.title = "床位信息";
      this.openBed = true;
      this.roomDataInfo = row;
    },

    // 添加框选择楼栋后
    async houseIdChange(id) {
      await this.getfloorList({
        houseId: id
      });
      this.form.floorId = null;
    },
    // 表格选中事件
    handleSelectionChange() { },
    // 获取部门信息
    department() {
      deptTreeSelect().then(res => {
        this.deptOptions = res.data;
      });
    },

    // 部门选中后

    handleChange(value) { },

    // 一键清空宿舍内的床位

    async empty(row) {
      this.$modal
        .confirm('是否确认清空宿舍为"' + row.roomNo + '"的入住数据？')
        .then(async () => {
          const { data, code } = await this.deleteUseBedByRoomIds({
            roomids: row.roomId
          });

          if (code == 200) {
            this.$message.success(`清除${row.roomNo}房间入住信息成功。`);
          }
        });
    }
  }
};
</script>